<template>
  <div>
    <!-- 搜索栏 -->
    <el-card id="search" class="box-card">
      <el-row>
        <el-col :span="20">
          <el-input v-model="searchModel.orderType" placeholder="订单类型" clearable />
          <el-button type="primary" round icon="el-icon-search" @click="getOrderList">查询</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 查询结果栏 -->
    <el-card>
      <el-table :data="orderDetailsList" style="width: 100%" height="400px">
        <el-table-column fixed label="#" width="50">
          <template slot-scope="scope">
            {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
          </template>
          <!--  {{(searchModel.pageNo-1) * searchModel.pageSize + scope.$index + 1}} -->
        </el-table-column>
        <el-table-column prop="orderId" label="订单ID" width="70" />
        <el-table-column prop="userId" label="用户ID" width="70" />
        <!-- <el-table-column prop="username" label="用户名" width="120" /> -->
        <el-table-column prop="username" label="用户名" width="120">
          <template slot-scope="scope">
            {{ scope.row.username }}
          </template>
        </el-table-column>
        <el-table-column prop="scheduledtime" label="预定时间" width="100" />
        <el-table-column prop="orderDate" label="下单时间" width="100" />
        <el-table-column prop="status" label="订单状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == '已下单'">已下单</el-tag>
            <el-tag v-else-if="scope.row.status == '已结束'" type="success">已结束</el-tag>
            <el-tag v-else-if="scope.row.status == '已取消'" type="warning">已取消</el-tag>
            <el-tag v-else type="danger">不知道</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="支付金额（元）" width="120" />
        <el-table-column prop="orderType" label="订单类型" width="120" />
        <el-table-column prop="orderType" label="对应名称" width="120">
          <template slot-scope="scope">
            <!-- 根据不同的订单类型显示对应的名称 -->
            <span v-if="scope.row.orderType === '餐饮店家预定订单'">{{ scope.row.foodbusinessname }}</span>
            <span v-else-if="scope.row.orderType === '民宿预定订单'">{{ scope.row.accommodationname }}</span>
            <span v-else-if="scope.row.orderType === '景点门票预定订单'">{{ scope.row.attractionname }}</span>
            <span v-else-if="scope.row.orderType === '景点路线预定订单'">{{ scope.row.routelistname }}</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="openEditUi(scope.row.orderId)" />
            <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteorder(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 订单信息编辑对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearform">
      <el-form ref="orderFromRef" :model="orderForm" :rules="rules">
        <el-form-item label="用户Id" prop="userId" :label-width="formLabelWidth">
          <el-input v-model="orderForm.userId" readonly="true" autocomplete="off" />
        </el-form-item>
        <!-- v-if="orderForm.id == null || orderForm.id == undefined" -->
        <el-form-item label="预定时间" prop="scheduledtime" :label-width="formLabelWidth">
          <div class="block">
            <span class="demonstration" />
            <el-date-picker v-model="orderForm.scheduledtime" type="datetime" placeholder="选择日期时间" />
          </div>
        </el-form-item>
        <el-form-item label="下单时间" prop="orderDate" :label-width="formLabelWidth">
          <template>
            <div class="block">
              <span class="demonstration" />
              <el-date-picker
                v-model="orderForm.orderDate"
                type="datetime"
                placeholder="选择日期时间"
                align="right"
                :picker-options="pickerOptions"
              />
            </div>
          </template>
        </el-form-item>
        <el-form-item label="订单状态" :label-width="formLabelWidth">
          <template>
            <el-select v-model="orderForm.status" clearable placeholder="请选择订单状态">
              <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-form-item>
        <!-- <el-form-item label="对应类型id" prop="orderSetId" :label-width="formLabelWidth">
          <el-input v-model="orderForm.orderSetId" readonly="true" autocomplete="off" />
        </el-form-item> -->
        <el-form-item label="订单类型" :label-width="formLabelWidth">
          <el-input v-model="orderForm.orderType" readonly="true" autocomplete="off" />
        </el-form-item>
        <el-form-item label="支付金额（元）" :label-width="formLabelWidth">
          <el-input v-model="orderForm.totalPrice" readonly="true" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrder">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import orderApi from '@/api/OrderManage'
import userApi from '@/api/userManage'
import foodbusinessApi from '@/api/FoodbusinessManage'
import accommodationApi from '@/api/AccommodationManage'
import attractionApi from '@/api/AttractionManage'
import routelistApi from '@/api/RoutelistManage'

export default {
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      value1: '',
      value2: '',

      options1: [{
        value: '已下单',
        label: '已下单'
      }, {
        value: '已结束',
        label: '已结束'
      }, {
        value: '已取消',
        label: '已取消'
      }, {
        value: '不知道',
        label: '不知道'
      }
      ],
      value: '',
      formLabelWidth: '130px',
      orderForm: {},
      dialogFormVisible: false,
      title: '',
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10
      },
      orderDetailsList: [],
      userMsgList: [],
      rules: {}
    }
  },
  created() {
    this.getOrderList()
  },
  methods: {
    handleOrderTypeChange() {
      // 根据选择的订单类型设置对应的订单id
      switch (this.orderForm.orderType) {
        case '餐饮店家预定订单':
          this.orderForm.foodbusinessId = this.orderForm.orderSetId // 示例订单id
          break
        case '民宿预定订单':
          this.orderForm.accommodationId = this.orderForm.orderSetId // 示例订单id
          break
        case '景点门票预定订单':
          this.orderForm.attractionId = this.orderForm.orderSetId // 示例订单id
          break
        case '景点路线预定订单':
          this.orderForm.routelistId = this.orderForm.orderSetId // 示例订单id
          break
        default:

          break
      }
    },
    Selectuser(userId, index) {
      userApi.getUserById(userId).then(response => {
        if (response.data == null) {
          this.$set(this.orderDetailsList[index], 'username', '该用户已注销')
        } else {
          // 添加新属性 'username' 到 this.orderDetailsList[index] 对象
          this.$set(this.orderDetailsList[index], 'username', response.data.username)
        }
        this.$set(this, 'orderDetailsList', this.orderDetailsList)
      })
    },
    Selectfoodbusiness(foodbusinessId, index) {
      if (!foodbusinessId) {
        this.$set(this.orderDetailsList[index], 'foodbusinessname', '该餐饮已注销')
        return
      }
      foodbusinessApi.getFoodbusinessById(foodbusinessId).then(response => {
        if (response.data == null) {
          this.$set(this.orderDetailsList[index], 'foodbusinessname', '该餐饮已注销')
        } else {
          this.$set(this.orderDetailsList[index], 'foodbusinessname', response.data.name)
        }
        // 控制台输出商家名称
        console.log('餐饮名称:', this.orderDetailsList[index].foodbusinessname)
        // 强制更新
        this.$forceUpdate()
      })
    },
    Selectaccommodation(accommodationId, index) {
      if (!accommodationId) {
        this.$set(this.orderDetailsList[index], 'accommodationname', '该民宿已注销')
        return
      }
      accommodationApi.getAccommodationById(accommodationId).then(response => {
        if (response.data == null) {
          this.$set(this.orderDetailsList[index], 'accommodationname', '该民宿已注销')
        } else {
          this.$set(this.orderDetailsList[index], 'accommodationname', response.data.name)
        }
        // 控制台输出商家名称
        console.log('民宿名称:', this.orderDetailsList[index].accommodationname)
        // 强制更新
        this.$forceUpdate()
      })
    },
    Selectattraction(attractionId, index) {
      if (!attractionId) {
        this.$set(this.orderDetailsList[index], 'attractionname', '该景点已删除')
        return
      }
      attractionApi.getAttractionById(attractionId).then(response => {
        if (response.data == null) {
          this.$set(this.orderDetailsList[index], 'attractionname', '该景点已删除')
        } else {
          this.$set(this.orderDetailsList[index], 'attractionname', response.data.name)
        }
        // 控制台输出商家名称
        console.log('景点名称:', this.orderDetailsList[index].attractionname)
        // 强制更新
        this.$forceUpdate()
      })
    },
    Selectroutelist(routelistId, index) {
      if (!routelistId) {
        this.$set(this.orderDetailsList[index], 'routelistname', '该旅游路线已删除')
        return
      }
      routelistApi.getRoutelistById(routelistId).then(response => {
        if (response.data == null) {
          this.$set(this.orderDetailsList[index], 'routelistname', '该旅游路线已删除')
        } else {
          this.$set(this.orderDetailsList[index], 'routelistname', response.data.name)
        }
        // 控制台输出商家名称
        console.log('旅游路线名称:', this.orderDetailsList[index].routelistname)
        // 强制更新
        this.$forceUpdate()
      })
    },
    deleteorder(order) {
      this.$confirm(`您确定要删除订单${order.username}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        orderApi.deleteById(order.orderId).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getOrderList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    saveOrder() {
      // 触发表单验证
      this.$refs.orderFromRef.validate((valid) => {
        if (valid) {
          // 提交请求到后台
          orderApi.saveOrder(this.orderForm).then(response => {
            // 成功提交的提示
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭对话框
            this.dialogFormVisible = false
            // 刷新数据
            this.getOrderList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 清除表单报错信息
    clearform() {
      this.orderForm = {}
      this.$refs.orderFromRef.clearValidate()
    },
    openEditUi(orderId) {
      if (orderId == null) {
        this.title = '新增订单'
      } else {
        this.title = '修改订单'
        // 根据id查数据
        orderApi.getOrderById(orderId).then(response => {
          this.orderForm = response.data
        })
      }
      this.dialogFormVisible = true
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getOrderList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getOrderList()
    },
    getOrderList() {
      this.searchModel.userId = this.$store.state.user.userId
      orderApi.getOrderList(this.searchModel).then(response => {
        // 清空原有数据
        this.orderDetailsList = []
        for (let i = 0; i < response.data.rows.length; i++) {
          this.orderDetailsList.push(response.data.rows[i])
          this.Selectuser(response.data.rows[i].userId, i)
          if (response.data.rows[i].foodbusinessId !== null && response.data.rows[i].foodbusinessId !== undefined) {
            this.Selectfoodbusiness(response.data.rows[i].foodbusinessId, i)
          } else {
            this.$set(this.orderDetailsList[i], 'foodbusinessname', '该餐饮不存在')
          }
          if (response.data.rows[i].accommodationId !== null && response.data.rows[i].accommodationId !== undefined) {
            this.Selectaccommodation(response.data.rows[i].accommodationId, i)
          } else {
            this.$set(this.orderDetailsList[i], 'accommodationname', '该民宿不存在')
          }
          if (response.data.rows[i].attractionId !== null && response.data.rows[i].attractionId !== undefined) {
            this.Selectattraction(response.data.rows[i].attractionId, i)
          } else {
            this.$set(this.orderDetailsList[i], 'attractionname', '该景点不存在')
          }
          if (response.data.rows[i].routelistId !== null && response.data.rows[i].routelistId !== undefined) {
            this.Selectroutelist(response.data.rows[i].routelistId, i)
          } else {
            this.$set(this.orderDetailsList[i], 'routelistname', '该旅游路线不存在')
          }
        }

        this.total = response.data.total
      })
    }
  }
}
</script>

<style lang="scss" scoped>
#search .el-input {
  width: 200px;
  margin-right: 10px;
}

.el-dialog .el-input {
  width: 200px;

}
</style>
